package cn.zh.stan.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import org.json.JSONException;
import org.json.JSONObject;

import javax.xml.transform.OutputKeys;

import cn.zh.stan.BaseUrl;
import cn.zh.stan.ITem.UserItem;
import cn.zh.stan.MyApplication;
import cn.zh.stan.R;
import cn.zh.stan.fragment.CarFragment;
import cn.zh.stan.fragment.HomeFragment;
import cn.zh.stan.fragment.MineFragment;
import cn.zh.stan.fragment.NotifyFragment;
import cn.zh.stan.fragment.OrderFragment;
import cn.zh.stan.util.ToastUtil;
import it.sephiroth.android.library.picasso.Picasso;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity {
   Fragment homeFragment,carfragment,orderfragment,notifragment,minfragment;
   RadioGroup mainrgroup;
   LayoutInflater inflater;
   FragmentManager fm;
   MyApplication mapp;
   String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        inflater=LayoutInflater.from(this);
        fm=getSupportFragmentManager();
        mapp= (MyApplication) getApplication();
        uid=mapp.getSp().getString("uid","");
        getUinfo();
        initv();
        PgyUpdateManager.register(MainActivity.this,
                new UpdateManagerListener() {
                    @Override
                    public void onUpdateAvailable(final String result) {
                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);
                        String sve=getVersion();
                        if (sve.equals(appBean.getVersionName())){
                            return;
                         }
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("更新")
                                .setMessage("   检测更新?")
                                .setNegativeButton(
                                        "确定",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                                } else {
                                                    startDownloadTask(MainActivity.this, appBean.getDownloadURL());
                                                }
                                            }
                                        }).show();
                    }
                    @Override
                    public void onNoUpdateAvailable() {
                    }
                });
            }


      private  void initv(){
          mainrgroup= (RadioGroup) findViewById(R.id.mainrgroup);
          mainrgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(RadioGroup radioGroup, int i) {
                  FragmentTransaction ft=fm.beginTransaction();
                  hideAllFragments(ft);
                  switch (i){
                      case R.id.menu_home:
                          if (null==homeFragment){
                              homeFragment = new HomeFragment();
                              ft.add(R.id.fram,homeFragment);
                              //如果当前fragment已经被构造，则显示出来
                          }else {
                              ft.show(homeFragment);
                          }
                          break;
                      case R.id.menu_car:
                          if (null==carfragment){
                              carfragment = new CarFragment();
                              ft.add(R.id.fram,carfragment);
                              //如果当前fragment已经被构造，则显示出来
                          }else {
                              ft.show(carfragment);
                          }
                          break;
                      case R.id.menu_order:
                          if (null==orderfragment){
                              orderfragment = new OrderFragment();
                              ft.add(R.id.fram,orderfragment);
                              //如果当前fragment已经被构造，则显示出来
                          }else {
                              ft.show(orderfragment);
                          }
                          break;
                      case R.id.menu_notification:
                          if (null==notifragment){
                              notifragment = new NotifyFragment();
                              ft.add(R.id.fram,notifragment);
                              //如果当前fragment已经被构造，则显示出来
                          }else {
                              ft.show(notifragment);
                          }
                          break;
                      case R.id.menu_mine:
                          if (null==minfragment){
                              minfragment = new MineFragment();
                              ft.add(R.id.fram,minfragment);
                              //如果当前fragment已经被构造，则显示出来
                          }else {
                              ft.show(minfragment);
                          }
                          break;
                       }
                  ft.commit();
                }
            });
          RadioButton menu_home= (RadioButton) findViewById(R.id.menu_home);
          menu_home.setChecked(true);
           }




   @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
       }
    private void hideAllFragments(FragmentTransaction ft){
        if (null != homeFragment){ft.hide(homeFragment);}
        if (null != carfragment){ft.hide(carfragment);}
        if (null != orderfragment){ft.hide(orderfragment);}
        if (null != notifragment){ft.hide(notifragment);}
        if (null != minfragment){ft.hide(minfragment);}
          }


    public void getUinfo(){
        OkHttpUtils.get(BaseUrl.men_getinfo)
                .params("userId",uid)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONObject Res=js.getJSONObject("Res");
                                String  Id=Res.getString("Id");
                                String MemberId=Res.getString("MemberId");
                                String TrueName=Res.getString("TrueName");
                                String Gender=Res.getString("Gender");
                                String  Birthday=Res.getString("Birthday");
                                String  Email=Res.getString("Email");
                                String  Phone=Res.getString("Phone");
                                String  IndexPic=Res.getString("IndexPic");
                                String  CreateTime=Res.getString("CreateTime");
                                String  IdCard1=Res.getString("IdCard1");
                                String  IdCard2=Res.getString("IdCard2");
                                String  Photo=Res.getString("Photo");
                                String  Status=Res.getString("Status");
                                String url="http://120.26.41.167:8092"+IndexPic;
                                UserItem userItem=new UserItem( Id,  MemberId,  TrueName,  Gender,  Birthday,  Email,  Phone,  url,  CreateTime,  IdCard1,  IdCard2, Photo, Status);
                                mapp.setUserItem(userItem);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
           }



 public String getUid(){

     return uid;
     }



    // 获取当前版本的版本号
    private String getVersion(){
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
      }




}
